package net.sesami.nhg.ebd.batch.email;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import net.sesami.nhg.ebd.batch.constants.IConstants;
import net.sesami.nhg.ebd.batch.exception.ApplicationException;
import net.sesami.nhg.ebd.batch.properties.ApplicationProperties;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;
import org.apache.log4j.Logger;

public class ApplicationEmailer {
	private static final Logger LOGGER = Logger
			.getLogger(ApplicationEmailer.class);
	private ApplicationProperties applicationProperties = new ApplicationProperties();

	public void sendExceptionEmail(String message, Throwable e) {
		try {
			String body = "";
			if (e instanceof ApplicationException) {
				body = this.getStackTraceAsString(((ApplicationException) e)
						.getException());
			} else {
				body = this.getStackTraceAsString(e);
			}

			Email email = new SimpleEmail();
			email.setHostName(applicationProperties
					.getProperty(IConstants.EmailConfig.HOST_NAME));
			email.setSmtpPort(Integer.valueOf(applicationProperties
					.getProperty(IConstants.EmailConfig.SMTP_PORT)));
			email.setFrom(
					applicationProperties
							.getProperty(IConstants.EmailConfig.EXCEPTION_NOTIFICATION_FROM_EMAIL),
					applicationProperties
							.getProperty(IConstants.EmailConfig.EXCEPTION_NOTIFICATION_FROM_NAME));
			if (e instanceof ApplicationException) {
				email.setSubject(((ApplicationException) e)
						.getExceptionMessage());
			} else {
				email.setSubject(message);
			}

			email.setMsg(body);
			String[] toAddresses = this
					.getEmailAddressArray(applicationProperties
							.getProperty(IConstants.EmailConfig.EXCEPTION_NOTIFICATION_TO_EMAIL));
			for (String emailAdddress : toAddresses) {
				email.addTo(emailAdddress);
			}

			email.send();
		} catch (Exception exception) {
			LOGGER.error("Error occured while sending exception notification",
					exception);
		}
	}

	public String getStackTraceAsString(Throwable e) {
		Writer result = new StringWriter();
		PrintWriter printWriter = new PrintWriter(result);
		e.printStackTrace(printWriter);
		String body = result.toString();
		System.out.println("*********************************");
		System.out.println(body);
		System.out.println("*********************************");
		return body;
	}

	private String[] getEmailAddressArray(String commaSeparatedEmails) {
		if (commaSeparatedEmails != null && !commaSeparatedEmails.isEmpty()) {
			String[] array = commaSeparatedEmails.split(",");
			return array;
		}

		return new String[] {};
	}
}
